<script setup>
import { ref } from 'vue'
import { courseAllService } from '@/api/course.js'
import { courseGradeService } from '@/api/statistic.js';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts'

const chert = ref()

const courseId = ref()

const courseName = ref('所有')

const courses = ref([])

const chartData = ref()

const courseList = async () => {
  try {
    let result = await courseAllService();
    courses.value = result.data;
  } catch (error) {
    console.log('Error fetching data:', error)
  }
}

courseList();

const getCourseGrade = async (courseId) => {
  if (courseId == undefined) {
    courseId = '';
  }

  try {
    let result = await courseGradeService(courseId);
    chartData.value = result.data;
  } catch (error) {
    console.log('Error fetching data:', error)
  }

  for (let i = 0; i < courses.value.length; i++) {
    if (courseId === courses.value[i].id) {
      courseName.value = courses.value[i].name
    }
  }

  var chart = echarts.init(chert.value)

  var option = (option = {
    title: {
      text: '课程[' + courseName.value + ']统计',
      subtext: 'Fake Data',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: 'Access From',
        type: 'pie',
        radius: '50%',
        data: chartData.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })

  chart.setOption(option);
}

</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>各课程学生成绩统计</span>
      </div>
    </template>

    <el-form inline>
      <el-form-item label="课程名称：" prop="courseId">
        <el-select v-model="courseId" placeholder="请选择课程">
          <el-option v-for="c in courses" :key="c.id" :label="c.name" :value="c.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="getCourseGrade(courseId); courseId = ''; courseName = '所有'">搜索</el-button>
        <el-button @click="courseId = ''; chartData = []">重置</el-button>
      </el-form-item>
    </el-form>

    <div ref="chert" class="chert" id="chert">
      <div v-if="courseId == null">
        <el-empty description="没有数据" />
      </div>
    </div>
  </el-card>
</template>

<style scoped>
.page-container {
  width: 100%;
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .chert {
    width: 700px;
    height: 400px;
  }
}
</style>